package com.taotao.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.mapper.ItemMapper;
import com.taotao.pojo.Item;
import com.taotao.pojo.ItemDesc;
import com.taotao.pojo.ItemParamItem;

@Service
public class ItemService extends BaseService<Item> {

	@Autowired
	private ItemDescService service;
	@Autowired
	private ItemParamItemService itemParamItemService;

	@Autowired
	private ItemMapper itemMapper;

	private static final Logger LOGGER = LoggerFactory.getLogger(ItemService.class);

	public void saveItem(Item item, String desc, String params) {

		item.setStatus(1);// 1表示上架
		item.setId(null);
		super.save(item);
		
		Long id = item.getId();
		if (LOGGER.isDebugEnabled())
			LOGGER.debug("新增用户id为:" + id);
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemId(id);
		itemDesc.setItemDesc(desc);
		service.save(itemDesc);
		
		if(StringUtils.isNotEmpty(params)){
			ItemParamItem itemParamItem = new ItemParamItem();
			itemParamItem.setItemId(item.getId());
			itemParamItem.setParamData(params);
			itemParamItemService.save(itemParamItem);
		}

	}

	public PageInfo<Item> queryPages(Integer page, Integer rows) {
		Example example = new Example(Item.class);
		example.setOrderByClause("updated DESC");
		example.createCriteria().andNotEqualTo("status", 3);
		PageHelper.startPage(page, rows);
		List<Item> list = itemMapper.selectByExample(example);
		return new PageInfo<Item>(list);
	}

	/**
	 * 商品的逻辑删除
	 * 
	 * @param ids
	 * @return
	 */
	public void updateByIds(List<Object> ids) {
		Example example = new Example(Item.class);
		example.createCriteria().andIn("id", ids);
		Item item = new Item();
		item.setStatus(3);
		this.getMapper().updateByExampleSelective(item, example);
	}

	/**
	 * 商品的编辑更新
	 * @param item
	 * @param itemDesc
	 */
	public void updateItem(Item item, String desc) {
		item.setCreated(null);
		item.setStatus(null);
		super.updateSelective(item);
		
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemDesc(desc);
		itemDesc.setItemId(item.getId());
		service.updateSelective(itemDesc);
		
	}
}
